package com.chanzany.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chanzany.srb.core.listener.ExcelDictDTOListener;
import com.chanzany.srb.core.mapper.DictMapper;
import com.chanzany.srb.core.pojo.dto.ExcelDictDTO;
import com.chanzany.srb.core.pojo.entity.Dict;
import com.chanzany.srb.core.service.DictService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author ChanZany
 * @since 2021-04-11
 */
@Service
@Slf4j
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {

    @Resource
    private DictMapper dictMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class, new ExcelDictDTOListener(dictMapper)).sheet().doRead();
        log.info("Excel导入成功");
    }

    //读取所有dict数据
    @Override
    public List<ExcelDictDTO> listDictData() {
        List<Dict> dictList = dictMapper.selectList(null);
        ArrayList<ExcelDictDTO> excelDictDTOS = new ArrayList<>(dictList.size());
        for (Dict dict : dictList) {
            excelDictDTOS.add(new ExcelDictDTO(dict));
        }
        return excelDictDTOS;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {
        //先查询redis中是否存在数据列表
        List<Dict> dictList = null;
        try {
            dictList = (List<Dict>)redisTemplate.opsForValue().get("srb:core:dictList:" + parentId);
            if (dictList!=null){
                log.info("从redis中取值");
                return dictList;
            }
        }catch (Exception e){
            log.error("redis服务器异常：{}", ExceptionUtils.getStackTrace(e));
        }

        log.info("从数据库中取值");
        dictList = dictMapper.selectList(new QueryWrapper<Dict>().eq("parent_id", parentId));
        //填充子节点的hasChildren字段
        dictList.forEach(dict -> {
            //找到把当前节点作为parent的子节点
            dict.setHasChildren(hasChildren(dict.getId()));
        });

        //将数据存入redis
        try {
            redisTemplate.opsForValue().set("srb:core:dictList:"+parentId,dictList,5, TimeUnit.MINUTES);
            log.info("数据存入redis");
        }catch (Exception e){
            log.error("redis服务器异常：{}", ExceptionUtils.getStackTrace(e));
        }
        return dictList;
    }

    /**
     * 判断当前id所在的节点下是否有子节点
     *
     * @param id
     * @return
     */
    private boolean hasChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        return dictMapper.selectCount(queryWrapper) > 0;
    }
}
